// mock/users.js
export default [
  {
    url: "/api/demo",
    method: "get",
    response: {
      code: 0,
      result: { info: "get请求成功" },
      message: "",
    },
  },
  {
    url: "/api/demo",
    method: "post",
    response: {
      code: 0,
      result: { info: "pot请求成功" },
      message: "",
    },
  },
  {
    url: "/api/login",
    method: "post",
    rawResponse: async (req, res) => {
      let reqbody = "";
      await new Promise((resolve) => {
        req.on("data", (chunk) => {
          reqbody += chunk;
        });
        req.on("end", () => resolve(undefined));
      });
      res.setHeader("Content-Type", "application/json");
      res.statusCode = 200;

      if (!!reqbody) {
        const body = JSON.parse(reqbody);
        console.log("body", body);
        const { name, password } = body;
        if (!!name && !!password) {
          return res.end(
            JSON.stringify({
              code: 0,
              result: { token: "123456", reToken: "456789" },
              message: "登录成功",
            })
          );
        }
      }

      res.statusCode = 401;
      return res.end(
        JSON.stringify({
          code: 0,
          result: {},
          message: "请输入账号、密码",
        })
      );
    },
  },
  {
    url: "/api/user",
    method: "get",
    rawResponse: async (req, res) => {
      res.setHeader("Content-Type", "application/json");
      const token = req.headers.authorization;
      res.statusCode = 200;

      console.log("token", token);

      if (!!token && token == "123456789") {
        return res.end(
          JSON.stringify({
            code: 0,
            result: {
              id: 1,
              name: "Alice",
              email: "alice@example.com",
            },
          })
        );
      }

      //   res.statusCode = 401;
      return res.end(
        JSON.stringify({
          code: 401,
          message: "请先登录/登录已过期",
          result: {},
        })
      );
    },
  },
  {
    url: "/api/refreshToken",
    method: "get",
    response: (req) => {
      if (req.query?.refreshToken == "456789") {
        return {
          code: 0,
          result: { token: "123456789", reToken: "456789" },
          message: "token刷新成功",
        };
      }

      return {
        code: 401,
        result: {},
        message: "token刷新失败",
      };
    },
  },
];
